/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.Actions;

import java.io.Serializable;

import controller.Forms.LoginForm;
import dao.UserDAO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Erro;
import model.User;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Adriano
 */
public class AuthenticateAction extends Action implements Serializable{
	
	final static Logger logger = Logger.getLogger(AuthenticateAction.class);

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            LoginForm lf = (LoginForm) form;
            User u = new User();

            u.setEmail(lf.getTxtLogin());
            u.setPassword(lf.getTxtPassword());
            UserDAO uDao = new UserDAO();
            u = (User) uDao.read(u);

            uDao.closeDAO();
            
            if (u == null) {
                request.getSession().setAttribute("ErroMSG", Erro.erroMsg[Erro.USUARIO_INVALIDO]);
                
                return mapping.findForward("erroAlias");
            }
            else {
                request.getSession().setAttribute("User", u);

                return mapping.findForward("homeAlias");
            }
        } catch (Exception e) {

            logger.error("AUTENTICAR_ACTION ",e);

            return mapping.findForward("erroAlias");
        }
    }

}
